<template>
  <j-modal title="管理跟踪号" :width="500" :visible.sync="modalVisible" :maskClosable="false">
    <a-button
      type="primary"
      icon="plus"
      style="margin-bottom: 15px"
      @click="formData.trackingNumberArr.push({ code: '' })"
      >添加</a-button
    >
    <a-form-model ref="form" :model="formData" :rules="rules">
      <a-table
        bordered
        :pagination="false"
        :columns="formColumns"
        :data-source="formData.trackingNumberArr"
        :rowKey="(r, index) => index"
      >
        <template #trackingNumber="text, record, index">
          <a-form-model-item
            :prop="'trackingNumberArr.' + index + '.code'"
            :rules="{
              required: true,
              message: '号码不能为空',
            }"
          >
            <a-input v-model="record.code" />
          </a-form-model-item>
        </template>
        <span slot="action" slot-scope="text, record, index">
          <a @click="formData.trackingNumberArr.splice(index, 1)">删除</a>
        </span>
      </a-table>
    </a-form-model>
    <template #footer>
      <a-button @click="modalVisible = false"> 取消 </a-button>
      <a-button type="primary" :loading="submitLoading" @click="handleOk"> 确定 </a-button>
    </template>
  </j-modal>
</template>

<script>
import { postFormAction } from '@/api/manage'

export default {
  data() {
    return {
      modalVisible: false,
      submitLoading: false,
      formData: {
        trackingNumberArr: [],
      },
      formColumns: [
        {
          title: '快递/物流号',
          scopedSlots: { customRender: 'trackingNumber' },
        },
        {
          title: '操作',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        updateTrackNo: '/hzkj-purchase/purchase/order/info/updateTrackNo',
      },
    }
  },
  methods: {
    api_open(id, trackingNumber) {
      this.formData = {
        id,
        trackingNumberArr: trackingNumber ? trackingNumber.split(',').map((i) => ({ code: i })) : [],
      }
      this.modalVisible = true
      this.submitLoading = false
    },
    // 产品提交
    handleOk() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          postFormAction(this.url.updateTrackNo, {
            id: this.formData.id,
            trackingNumber: this.formData.trackingNumberArr.map((i) => i.code).join(','),
          })
            .then((res) => {
              if (res.success) {
                this.$message.success('修改成功')
                this.$emit('submit')
                this.modalVisible = false
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },
  },
}
</script>
